from django import http
from django.shortcuts import render

# Create your views here.

from django.views import View

from apps.verifications.conatants import SMS_CODE_EXPIRE_TIME
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE
import logging
logger = logging.getLogger('django')

class ImageCode(View):
    def get(self,request,uuid):
        from libs.captcha.captcha import captcha
        text,image = captcha.generate_captcha()
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s'%uuid,120,text)
        return http.HttpResponse(image,content_type='image/jpeg')

class SMSCodeView(View):
    def get(self,request,mobile):
        # 1.后端要接收数据
        params = request.GET
        uuid = params.get('image_code_id')
        text_client = params.get('image_code')
        # 2.验证数据
        # 2.1连接redis
        from django_redis import get_redis_connection

        try:
            redis_conn = get_redis_connection("code")
            # 2.2根据uuid获取redis中的数据
            text_server = redis_conn.get('img_%s'%uuid)
            # 2.3redis中的图片验证码有可能过期
            if text_server is None:
                return http.HttpResponseBadRequest("图片验证码过期")
            # 2.4比对
            if text_server.decode().lower() != text_client.lower():
                return http.HttpResponseBadRequest('验证码不正确')
            # 2.5删除图片验证码
            redis_conn.delete('img_%s'%uuid)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest("数据库连接问题")
        send_flag = redis_conn.get('send_flag_%s'%mobile)
        if send_flag is not None:
            return http.HttpResponseBadRequest('操作太频繁')
        # 3.生成短信验证码
        from random import randint
        sms_code = '%06d'%randint(0,999999)
        # 4.保存短信验证码
        redis_conn.setex('sms_%s'%mobile,SMS_CODE_EXPIRE_TIME,sms_code)
        redis_conn.setex('send_flag_%s'%mobile,60,1)
        # 5.发送短信验证码
        CCP().send_template_sms(mobile,[sms_code,5],1)
        # 6.返回响应
        return http.JsonResponse({'code':RETCODE.OK})
